package com.api.component;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

import org.springframework.stereotype.Component;

import com.api.common.exception.ParamException;
import com.api.model.request.TestRequest;

import io.swagger.annotations.ApiModelProperty;

@Component
public class RequestComponent {
	/**
	 * 验证参数必传
	 * 
	 * @param Body
	 * @param requestClass
	 * @throws IntrospectionException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public void checkBody(Object Body, Class requestClass) {
		try {
			Field[] arr = requestClass.getDeclaredFields();
			for (Field field : arr) {
				ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
				if (apiModelProperty.required()) {
					PropertyDescriptor pd = new PropertyDescriptor(field.getName(), requestClass);
					// 获得get方法
					Method getMethod = pd.getReadMethod();
					// 执行get方法返回一个Object
					Object obj = getMethod.invoke(Body);
					if (obj instanceof Long) {
						long l = (long) obj;
						if (l < 1) {
							throw new ParamException(field.getName() + "参数不能为空");
						}
					}
					if (Objects.isNull(obj)) {
						throw new ParamException(field.getName() + "参数不能为空");
					}
				}
			}
		} catch (ParamException e) {
			// TODO: handle exception
			throw new ParamException(e.getMessage());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}
